﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：RefreshTokenService.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Threading.Tasks;
using TongTongMall.Common.AutoMapper;
using TongTongMall.Domain.Repositories.Repositories;
using TongTongMall.MallWeb.ApplicationToken.Dto;
using TongTongMall.MallWeb.Core.Authorization;
using TongTongMall.UI;

namespace TongTongMall.MallWeb.Application.Token
{
    public class RefreshTokenService : MallWebApplicationServiceBase, IRefreshTokenService
    {
        private readonly IRepository<RefreshToken, string> _refreshTokenRepository;

        public RefreshTokenService(IRepository<RefreshToken, string> refreshTokenRepository)
        {
            _refreshTokenRepository = refreshTokenRepository;
        }

        public async Task<RefreshTokenDto> Get(string tokenId, long clientId)
        {
            var model = await _refreshTokenRepository.FirstOrDefaultAsync(new { Id = tokenId, ClientId = clientId });
            return model.MapTo<RefreshTokenDto>();
        }

        public async Task<bool> Remove(string tokenId)
        {
            return await _refreshTokenRepository.DeleteAsync(new { Id = tokenId });
        }

        public async Task<bool> Save(RefreshTokenDto token)
        {
            var isSuccess = false;
            try
            {
                //根据clientid与登录用户名 获取当前用户是否已经存在refreshtoken，存在进行删除
                await _refreshTokenRepository.DeleteAsync(new
                {
                    ClientId = token.ClientId,
                    UserID = token.UserID,
                    AuthorizationPlatFrom = token.AuthorizationPlatFrom
                });
                var model = token.MapTo<RefreshToken>();
                var identryid = await _refreshTokenRepository.InsertAsync(model);
                isSuccess = !string.IsNullOrEmpty(identryid);

            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
            return isSuccess;
        }
    }
}
